const { Model, DataTypes } = require('sequelize');
const sequelize = require('../config/database');
const logger = require('../utils/logger');

class Field extends Model {
  static async ensureCertNumberField() {
    try {
      const certNumberField = await this.findByPk(1);
      if (!certNumberField) {
        logger.info('Creating default certificate number field');
        await this.create({
          id: 1,
          name: '证书编号',
          field_name: 'cert_number',
          description: '证书的唯一编号',
          required: true
        });
        logger.info('Default certificate number field created successfully');
      }
    } catch (error) {
      logger.error('Error ensuring certificate number field:', error);
      throw error;
    }
  }

  // 获取下一个可用的 id（总是获取最大 ID + 1）
  static async getNextId() {
    try {
      // 获取最大的 id
      const result = await this.findOne({
        attributes: [[sequelize.fn('MAX', sequelize.col('id')), 'maxId']],
        raw: true
      });
      
      const maxId = result.maxId || 0;
      logger.info('Current max field ID:', maxId);
      
      // 如果没有字段或最大 ID 小于 1，返回 2（因为 1 是证书编号）
      if (maxId < 1) {
        return 2;
      }
      
      // 返回最大 ID + 1
      logger.info('Next field ID will be:', maxId + 1);
      return maxId + 1;
      
    } catch (error) {
      logger.error('Error in getNextId:', error);
      throw new Error('获取下一个可用 ID 失败');
    }
  }
}

Field.init({
  id: {
    type: DataTypes.INTEGER,
    primaryKey: true,
    autoIncrement: false
  },
  name: {
    type: DataTypes.STRING(255),
    allowNull: false,
    comment: '字段显示名称',
    validate: {
      notEmpty: {
        msg: '字段名称不能为空'
      }
    }
  },
  field_name: {
    type: DataTypes.STRING(255),
    allowNull: false,
    comment: '字段在数据库中的名称',
    validate: {
      notEmpty: {
        msg: '字段标识不能为空'
      }
    }
  },
  description: {
    type: DataTypes.TEXT,
    allowNull: true,
    comment: '字段描述'
  },
  required: {
    type: DataTypes.BOOLEAN,
    allowNull: false,
    defaultValue: false,
    comment: '是否必填'
  }
}, {
  sequelize,
  modelName: 'Field',
  tableName: 'fields',
  timestamps: true,
  underscored: true,
  indexes: [
    {
      unique: true,
      fields: ['name', 'field_name'],
      name: 'fields_unique_index'
    }
  ],
  hooks: {
    beforeUpdate: async (field) => {
      if (field.id <= 8) {
        throw new Error('系统字段不能修改');
      }
    },
    beforeDestroy: async (field) => {
      if (field.id <= 8) {
        throw new Error('系统字段不能删除');
      }
    }
  }
});

// 确保在模型初始化后创建证书编号字段
Field.afterSync(async () => {
  try {
    await Field.ensureCertNumberField();
  } catch (error) {
    logger.error('Error after sync:', error);
  }
});

module.exports = Field; 